package cn.com.ghy.android.widget.salemag;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnFocusChangeListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import cn.com.ghy.android.bean.MatnrInfoBean;
import cn.com.ghy.android.bean.YGOrderDetailInfoBean;
import cn.com.ghy.android.bean.YGQueryInfoBean;
import cn.com.ghy.android.exception.DisposeException;
import cn.com.ghy.android.service.YgOrderOpeService;
import cn.com.ghy.android.style.CustomProgressDialog;
import cn.com.ghy.android.util.CommonStatic;
import cn.com.ghy.android.util.CommonUtil;
import cn.com.ghy.android.widget.ComStaticApp;
import cn.com.ghy.android.widget.R;

public class SaleOrderDetailInfo extends Activity {

	private EditText txtDnm;
	private EditText txtBismt;
	private Button btnBismt;
	private Spinner spiMatnr;
	private EditText txtOrdernum;
	private EditText txtOrderprice;
	private TextView txtVolum;
	private TextView txtVoleh;
	private EditText txtWerks;
	private Button btnWerks;
	private EditText txtLgort;
	private Button btnLgort;
	private Button btnConfirm;
	private ProgressDialog progressDialog;

	private Intent intent;

	private HttpThread httpThread;

	private Exception error;
	private DisposeException disposeException;

	private List<MatnrInfoBean> matnrInfoBeanList = new ArrayList<MatnrInfoBean>();
	private Map<String, String> mapValue = new HashMap<String, String>();
	private Map<Integer, KeyEditText> mapEditText = new HashMap<Integer, KeyEditText>();
	private List<YGQueryInfoBean> yGQueryInfoBeanList;
	private YGOrderDetailInfoBean yGOrderDetailInfoBean;
	private int position;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.sale_order_detail_info);
		findView();
		getSession();
		addListener();
		if (position != -1 && yGOrderDetailInfoBean != null) {
			setView();
		} else {
			yGOrderDetailInfoBean = new YGOrderDetailInfoBean();
		}
	}

	private void findView() {
		txtDnm = (EditText) findViewById(R.id.txtDnm);
		txtBismt = (EditText) findViewById(R.id.txtBismt);
		btnBismt = (Button) findViewById(R.id.btnBismt);
		spiMatnr = (Spinner) findViewById(R.id.spiMatnr);
		txtOrdernum = (EditText) findViewById(R.id.txtOrdernum);
		txtOrderprice = (EditText) findViewById(R.id.txtOrderprice);
		txtVolum = (TextView) findViewById(R.id.txtVolum);
		txtVoleh = (TextView) findViewById(R.id.txtVoleh);
		txtWerks = (EditText) findViewById(R.id.txtWerks);
		btnWerks = (Button) findViewById(R.id.btnWerks);
		txtLgort = (EditText) findViewById(R.id.txtLgort);
		btnLgort = (Button) findViewById(R.id.btnLgort);
		btnConfirm = (Button) findViewById(R.id.btnConfirm);

		mapEditText.put(R.id.btnWerks, new KeyEditText("WERKS", txtWerks));
		mapEditText.put(R.id.btnLgort, new KeyEditText("LGORT", txtLgort));
	}

	private void getSession() {
		disposeException = ((ComStaticApp) getApplication()).getDisposeException();
		position = this.getIntent().getIntExtra("position", -1);
		yGOrderDetailInfoBean = (YGOrderDetailInfoBean) this.getIntent().getSerializableExtra(
				"yGOrderDetailInfoBean");
	}

	private void setView() {
		txtDnm.setText(yGOrderDetailInfoBean.getDnm());
		txtBismt.setText(yGOrderDetailInfoBean.getBismt());
		txtOrdernum.setText(yGOrderDetailInfoBean.getOrdernum());
		txtOrderprice.setText(yGOrderDetailInfoBean.getOrderprice());
		txtVolum.setText(yGOrderDetailInfoBean.getVolum());
		txtVoleh.setText(yGOrderDetailInfoBean.getVoleh());
		txtWerks.setText(yGOrderDetailInfoBean.getWerks());
		txtLgort.setText(yGOrderDetailInfoBean.getLgort());

		MatnrInfoBean bean = new MatnrInfoBean();
		bean.setMatnr(yGOrderDetailInfoBean.getMatnr());
		bean.setVoleh(yGOrderDetailInfoBean.getVoleh());
		bean.setVolum(yGOrderDetailInfoBean.getVolum());
		matnrInfoBeanList.add(bean);
		ArrayAdapter<MatnrInfoBean> adapter = //
		new ArrayAdapter<MatnrInfoBean>(SaleOrderDetailInfo.this,
				android.R.layout.simple_spinner_item, matnrInfoBeanList);
		adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		spiMatnr.setAdapter(adapter);

		btnConfirm.setText("修改");
	}

	private void addListener() {
		txtDnm.setKeyListener(CommonUtil.charNumListener);

		txtBismt.setKeyListener(CommonUtil.charNumListener);
		txtBismt.setOnFocusChangeListener(CommonUtil.editTextToUpperCaseListener);

		btnBismt.setOnClickListener(btnListenerEvent);
		spiMatnr.setOnItemSelectedListener(spiListener);
		btnWerks.setOnClickListener(btnListenerEvent);
		btnLgort.setOnClickListener(btnListenerEvent);
		btnConfirm.setOnClickListener(btnListenerEvent);

		txtOrderprice.addTextChangedListener(CommonUtil.decimalListener);
		txtOrderprice.setOnFocusChangeListener(new OnFocusChangeListener() {
			public void onFocusChange(View v, boolean hasFocus) {
				String str = ((EditText) v).getText().toString();
				if (!hasFocus && !"".equals(str)) {
					if (Double.parseDouble(str) > 500 || Double.parseDouble(str) < 0) {
						Toast.makeText(SaleOrderDetailInfo.this, //
								"单价不能超过500元", Toast.LENGTH_SHORT).show();
						txtOrderprice.setText("");
					}
				}
			}
		});
	}

	private View.OnClickListener btnListenerEvent = new View.OnClickListener() {
		@Override
		public void onClick(View v) {
			switch (v.getId()) {
				case R.id.btnBismt :
					if ("".equals(txtBismt.getText().toString().trim())) {
						Toast.makeText(SaleOrderDetailInfo.this, //
								"请输入要查询的SKU", Toast.LENGTH_SHORT).show();
						break;
					}
					txtBismt.setText(txtBismt.getText().toString().trim().toUpperCase());
					operate(R.id.btnBismt);
					break;
				case R.id.btnWerks :
					operate(R.id.btnWerks);
					break;
				case R.id.btnLgort :
					if ("".equals(txtWerks.getText().toString().trim())) {
						Toast.makeText(SaleOrderDetailInfo.this, //
								"请输入工厂", Toast.LENGTH_SHORT).show();
						break;
					}
					operate(R.id.btnLgort);
					break;
				case R.id.btnConfirm :
					String dnm = txtDnm.getText().toString().trim();
					if ("".equals(dnm)) {
						Toast.makeText(SaleOrderDetailInfo.this, //
								"请输入店内码", Toast.LENGTH_SHORT).show();
						break;
					}
					String bismt = txtBismt.getText().toString().trim();
					if ("".equals(bismt)) {
						Toast.makeText(SaleOrderDetailInfo.this, //
								"请输入SKU", Toast.LENGTH_SHORT).show();
						break;
					}
					if (yGOrderDetailInfoBean.getMatnr() == null //
							|| "".equals(yGOrderDetailInfoBean.getMatnr())) {
						Toast.makeText(SaleOrderDetailInfo.this, //
								"请选择物料号", Toast.LENGTH_SHORT).show();
						break;
					}
					String ordernum = txtOrdernum.getText().toString().trim();
					if ("".equals(ordernum) || !ordernum.matches("^[0-9]*[1-9][0-9]*$")) {
						Toast.makeText(SaleOrderDetailInfo.this, //
								"请输入数量", Toast.LENGTH_SHORT).show();
						break;
					}
					String orderprice = txtOrderprice.getText().toString().trim();
					if ("".equals(orderprice)
							|| !orderprice
									.matches("(([1-9][0-9]{0,3}((\\.[0-9]{1,2}){0,1}))|(0\\.[0-9]{1,2}))")) {
						Toast.makeText(SaleOrderDetailInfo.this, //
								"请输入单价", Toast.LENGTH_SHORT).show();
						break;
					}
					if (Double.parseDouble(orderprice) > 500 //
							|| Double.parseDouble(orderprice) <= 0) {
						Toast.makeText(SaleOrderDetailInfo.this, //
								"单价不能超过500元或不能为0!", Toast.LENGTH_SHORT).show();
						break;
					}
					String werks = txtWerks.getText().toString().trim();
					if ("".equals(werks)) {
						Toast.makeText(SaleOrderDetailInfo.this, //
								"请输入工厂", Toast.LENGTH_SHORT).show();
						break;
					}
					String lgort = txtLgort.getText().toString().trim();
					if ("".equals(lgort)) {
						Toast.makeText(SaleOrderDetailInfo.this, //
								"请输入库存地点", Toast.LENGTH_SHORT).show();
						break;
					}
					yGOrderDetailInfoBean.setDnm(dnm);
					yGOrderDetailInfoBean.setBismt(bismt);
					yGOrderDetailInfoBean.setOrdernum(Integer.parseInt(ordernum) + "");
					yGOrderDetailInfoBean.setOrderprice(Double.parseDouble(orderprice) + "");
					yGOrderDetailInfoBean.setWerks(werks);
					yGOrderDetailInfoBean.setLgort(lgort);
					yGOrderDetailInfoBean.setUnit("KAR");

					java.text.DecimalFormat df = new java.text.DecimalFormat("######0.00");
					double orderMoney = Integer.parseInt(ordernum) * Double.parseDouble(orderprice);
					yGOrderDetailInfoBean.setTotalprice("" + df.format(orderMoney));

					Bundle bundle = new Bundle();
					bundle.putSerializable("yGOrderDetailInfoBean", yGOrderDetailInfoBean);
					bundle.putInt("position", position);
					intent = new Intent();
					intent.putExtras(bundle);
					SaleOrderDetailInfo.this.setResult(RESULT_OK, intent);
					SaleOrderDetailInfo.this.finish();
					break;
				default :
					break;
			}
		}
	};

	private OnItemSelectedListener spiListener = new OnItemSelectedListener() {
		public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
			MatnrInfoBean bean = (MatnrInfoBean) parent.getItemAtPosition(position);
			txtVolum.setText(bean.getVolum());
			txtVoleh.setText(bean.getVoleh());

			yGOrderDetailInfoBean.setMatnr(bean.getMatnr());
			yGOrderDetailInfoBean.setVolum(txtVolum.getText().toString().trim());
			yGOrderDetailInfoBean.setVoleh(txtVoleh.getText().toString().trim());
		}

		public void onNothingSelected(AdapterView<?> parent) {

		}
	};

	private void operate(int opcode) {
		progressDialog = new CustomProgressDialog(SaleOrderDetailInfo.this);
		progressDialog.setButton("取消", new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				httpThread.stopSendMsg();
			}
		});
		progressDialog.show();

		httpThread = new HttpThread(opcode);
		Thread thread = new Thread(httpThread);
		thread.start();
	}

	private class HttpThread implements Runnable {
		private int opcode;

		public HttpThread(int opcode) {
			this.opcode = opcode;
		}

		private boolean isSendMsg = true;

		@Override
		public void run() {
			Message message = handler.obtainMessage();
			YgOrderOpeService service = new YgOrderOpeService();
			try {
				switch (opcode) {
					case R.id.btnBismt :
						matnrInfoBeanList = service.GetMatnrList(txtBismt.getText().toString()
								.trim());
						break;
					case R.id.btnWerks :
					case R.id.btnLgort :
						Iterator<Entry<Integer, KeyEditText>> it = mapEditText.entrySet()
								.iterator();
						while (it.hasNext()) {
							int key = it.next().getKey();
							String value = mapEditText.get(key).getEditText().getText().toString();
							mapValue.put(mapEditText.get(key).getKey(), value);
						}
						yGQueryInfoBeanList = service.GetSlt(mapValue, mapEditText.get(opcode)
								.getKey());
						break;
					default :
						break;
				}
			} catch (Exception e) {
				opcode = CommonStatic.ERROR_CODE;
				error = e;
			}
			if (isSendMsg) {
				message.what = opcode;
				handler.sendMessage(message);
			}
		}

		public void stopSendMsg() {
			isSendMsg = false;
		}

		@SuppressWarnings("unused")
		public void openSendMsg() {
			isSendMsg = true;
		}
	}

	private Handler handler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			progressDialog.dismiss();
			switch (msg.what) {
				case R.id.btnBismt :
					if (matnrInfoBeanList.size() == 0) {
						Toast.makeText(SaleOrderDetailInfo.this, //
								"输入的SKU不存在", Toast.LENGTH_SHORT).show();
						txtVolum.setText("");
						txtVoleh.setText("");
					}
					ArrayAdapter<MatnrInfoBean> adapter = //
					new ArrayAdapter<MatnrInfoBean>(SaleOrderDetailInfo.this,
							android.R.layout.simple_spinner_item, matnrInfoBeanList);
					adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
					spiMatnr.setAdapter(adapter);
					break;
				case R.id.btnWerks :
				case R.id.btnLgort :
					Bundle bundle = new Bundle();
					bundle.putSerializable("queryInfoList", (Serializable) yGQueryInfoBeanList);
					bundle.putInt("btnRId", msg.what);
					bundle.putString("key", mapEditText.get(msg.what).getKey());
					bundle.putString("value", mapEditText.get(msg.what).getEditText().getText()
							.toString());
					bundle.putSerializable("mapValue", (Serializable) mapValue);
					intent = new Intent(SaleOrderDetailInfo.this, SaleOrderBaseInfoQuery.class);
					intent.putExtras(bundle);
					SaleOrderDetailInfo.this.startActivityForResult(intent,
							R.layout.sale_order_baseinfo_query);
					break;
				case CommonStatic.ERROR_CODE :
					disposeException.handleException(error);
					break;
				default :
					break;
			}
		}
	};

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		switch (requestCode) {
			case R.layout.sale_order_baseinfo_query :
				if (resultCode == RESULT_OK) {
					Bundle bundleForResult = data.getExtras();
					int btnRId = bundleForResult.getInt("btnRId");
					String value = bundleForResult.getString("value");
					KeyEditText keyEditText = mapEditText.get(btnRId);
					if (keyEditText != null) {
						keyEditText.getEditText().setText(value);
					}
				}
				break;
			default :
				break;
		}
	}

	private class KeyEditText {
		private String key;
		private EditText editText;

		public KeyEditText(String key, EditText editText) {
			this.key = key;
			this.editText = editText;
		}

		public String getKey() {
			return key;
		}

		public EditText getEditText() {
			return editText;
		}
	}
}
